package com.zhb.scanner.utils

import android.media.MediaPlayer
import com.zhb.scanner.R
import com.zhb.scanner.Scanner
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.io.IOException

/**
 * Created by HongboZhao on 2021/1/12.
 */
object Player {
    fun playMp3() {
        runBlocking(Dispatchers.IO) {
            // 获取mp3文件的路径
            val mediaPlayer = MediaPlayer()
            if (Scanner.appContext != null) {
                val file = Scanner.appContext!!.resources.openRawResourceFd(R.raw.id_card_beep)
                try {
                    mediaPlayer.setDataSource(
                        file.fileDescriptor, file.startOffset,
                        file.length
                    )
                    mediaPlayer.prepare()
                    mediaPlayer.start()
                    delay(mediaPlayer.duration.toLong())
                    mediaPlayer.stop()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                mediaPlayer.release()
            }
        }
    }
}